package com.cbs.android.module.user.user.module;

import com.cbs.android.component.applicationutils.Global;
import com.cbs.android.component.applicationutils.network.CBSRequest;
import com.cbs.android.component.network.Request;
import com.cbs.android.component.network.Response;
import com.cbs.android.component.network.ResponseHandler;
import com.cbs.android.module.user.user.UserModule;
import com.cbs.android.module.user.user.handler.ModuleHandler;

import java.net.HttpURLConnection;

import okhttp3.FormBody;
import okhttp3.RequestBody;

/**
 * Created by broche on 11/3/15.
 */
public class UserModuleForgotPassword {
    private static final String UrlTpl = "%s/user/api/v1/users/%s/password";
    private String username;
    private String password;
    private String verifyCode;
    private ModuleHandler moduleHandler;

    public UserModuleForgotPassword(String username, String password, String verifyCode, ModuleHandler moduleHandler) {
        this.username = username;
        this.password = password;
        this.verifyCode = verifyCode;
        this.moduleHandler = moduleHandler;
    }

    public void start() {
        RequestBody requestBody = new FormBody.Builder()
                .add("newpassword", UserModule.getPassword(password))
                .add("verifycode", verifyCode)
                .build();
        Request request = new CBSRequest(String.format(UrlTpl, Global.getServerHost(), username))
                .put(requestBody)
                .setResponseHandler(new ResponseHandler() {
                    @Override
                    public void onResponse(Response response) {
                        if (response.getCode() == HttpURLConnection.HTTP_CREATED) {
                            if (moduleHandler != null) {
                                moduleHandler.onSuccess(response.getResult());
                            }
                        } else {
                            if (moduleHandler != null) {
                                moduleHandler.onFailure(response.getCode(), response.getResult().toString());
                            }
                        }
                    }

                    @Override
                    public void onException(Request request, Exception e) {
                        if (moduleHandler != null) {
                            moduleHandler.onException(e);
                        }
                    }
                });
        UserModule.getHttpClient().send(request);
    }
}
